package com.zhu.responder.websocker.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class MyNettyServerHandler extends SimpleChannelInboundHandler {
 
    private ChannelGroup channels;
 
    public MyNettyServerHandler(ChannelGroup channels){
        this.channels=channels;
    }
 
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("读取客户端消息！");
        if (null==msg){
            log.info("数据为空");
           return;
        }
        //第一次读请求是http连接而不是数据
        if (msg instanceof FullHttpRequest){
            FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;
            log.info("第一次http请求："+fullHttpRequest);
        }
        //正常的数据
        else if (msg instanceof TextWebSocketFrame){
            TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) msg;
            log.info("客户端消息："+textWebSocketFrame.text());
        }
    }
 
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端连接成功！");
        channels.add(ctx.channel());
    }
 
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端断开连接！");
        channels.remove(ctx.channel());
    }
}